package com.dc.bobaoge.project.v2.to.v3.business.core.method.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dc.bobaoge.base.entity.core.po.ContactUser;
import com.dc.bobaoge.base.entity.core.po.SystemUserExtraInfo;
import com.dc.bobaoge.base.mapper.core.ContactUserMapper;
import com.dc.bobaoge.base.mapper.core.SystemUserExtraInfoMapper;
import com.dc.bobaoge.project.base.core.old.entity.OldCoreUser;
import com.dc.bobaoge.project.base.core.old.mapper.OldCoreUserMapper;
import com.dc.bobaoge.project.base.core.util.WalletUtil;
import com.own.business.sync.trigger.base.entity.SyncTrigger;
import com.own.business.sync.trigger.base.method.ResolveMethod;
import com.own.business.system.account.common.em.AccountType;
import com.own.business.system.account.entity.SystemAccount;
import com.own.business.system.account.mapper.SystemAccountMapper;
import com.own.business.system.user.entity.po.SystemUser;
import com.own.business.system.user.entity.po.SystemUserInfo;
import com.own.business.system.user.mapper.SystemUserInfoMapper;
import com.own.business.system.user.mapper.SystemUserMapper;
import com.own.business.wallet.mapper.WalletMapper;
import com.own.component.common.exception.BusinessSimpleException;
import com.own.entity.tuple.Tuple;
import com.own.entity.tuple.Tuple2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * UserResolveMethod
 *
 * @author chenxueli
 * @date 2024-01-16 13:48:55
 */
@Slf4j
@Component
public class UserResolveMethod implements ResolveMethod {

    @Resource
    private SystemUserMapper systemUserMapper;
    @Resource
    private SystemAccountMapper systemAccountMapper;
    @Resource
    private SystemUserInfoMapper systemUserInfoMapper;
    @Resource
    private SystemUserExtraInfoMapper systemUserExtraInfoMapper;
    @Resource
    private ContactUserMapper contactUserMapper;
    @Resource
    private WalletMapper walletMapper;

    @Resource
    private OldCoreUserMapper oldCoreUserMapper;

    @Resource
    private UserUpdateStateResolveMethod userUpdateStateResolveMethod;
    @Resource
    private UserUpdateExtraInfoResolveMethod userUpdateExtraInfoResolveMethod;

    @Resource
    private WalletUtil walletUtil;

    /**
     * 修改的处理方法
     *
     * @param trigger 日志信息
     */
    @Override
    public void update(SyncTrigger trigger) {
        throw new BusinessSimpleException("不支持的操作");
    }

    /**
     * 新增的处理方法
     *
     * @param trigger 日志信息
     */
    @Override
    public void add(SyncTrigger trigger) {
        // 查询用户信息是否存在
        var oldCoreUser = oldCoreUserMapper.selectById(trigger.getTargetId());
        if (oldCoreUser == null) {
            throw new BusinessSimpleException("用户信息不存在");
        }
        // 查询是否已经存在当前用户了
        var systemUser = systemUserMapper.selectById(oldCoreUser.getUserId());
        if (systemUser == null) {
            add(trigger, oldCoreUser);
        }
    }

    /**
     * 新增用户信息
     *
     * @param trigger     日志信息
     * @param oldCoreUser 旧数据库用户数据
     */
    public void add(SyncTrigger trigger, OldCoreUser oldCoreUser) {
        // 新增用户的基本信息
        var user = buildCommonUserBaseInfo(new SystemUser(), oldCoreUser);
        systemUserMapper.insert(user);
        // 账号信息（手机验证码登录的账号）
        checkAndBuildPhoneAccount(oldCoreUser, oldCoreUser.getUserPhone(), AccountType.PHONE.type(), null);
        // 账号信息（手机号密码登录的账号）
        var accountName = StringUtils.isNotBlank(oldCoreUser.getUserAccount()) ? oldCoreUser.getUserAccount() : oldCoreUser.getUserPhone();
        checkAndBuildPhoneAccount(oldCoreUser, accountName, AccountType.TEXT.type(), oldCoreUser.getUserPwd());
        // 用户详细信息
        var userInfo = buildCommonUserDetailInfo(new SystemUserInfo(), oldCoreUser);
        systemUserInfoMapper.insert(userInfo);
        var extraInfo = userUpdateExtraInfoResolveMethod.buildCommonUserExtraInfo(new SystemUserExtraInfo(), oldCoreUser);
        systemUserExtraInfoMapper.insert(extraInfo);
        // 新增用户的联系人信息
        var contactUser = buildCommonUserContactInfo(new ContactUser(), oldCoreUser);
        contactUserMapper.insert(contactUser);
        // 初始化钱包信息
        walletUtil.checkAndInit(oldCoreUser.getUserId(), oldCoreUser.getUserPayPwd());
    }

    /**
     * 创建公共的联系人信息
     *
     * @param contactUser 联系人信息
     * @param oldCoreUser 旧数据库用户数据
     * @return 联系人信息
     */
    private ContactUser buildCommonUserContactInfo(ContactUser contactUser, OldCoreUser oldCoreUser) {
        contactUser.setFkUserId(oldCoreUser.getUserId());
        contactUser.setName("");
        contactUser.setPhone(oldCoreUser.getUserPhone());
        contactUser.setIsDefault(1);
        contactUser.setAllowEdit(1);
        contactUser.setAllowDelete(1);
        return contactUser;
    }

    /**
     * 创建用户的详细信息
     *
     * @param userInfo    用户信息
     * @param oldCoreUser 旧数据库用户数据
     * @return 用户的详细信息
     */
    private SystemUserInfo buildCommonUserDetailInfo(SystemUserInfo userInfo, OldCoreUser oldCoreUser) {
        userInfo.setPhone(oldCoreUser.getUserPhone());
        userInfo.setFkUserId(oldCoreUser.getUserId());
        return userInfo;
    }

    /**
     * 创建手机验证码登录的账号信息
     *
     * @param oldCoreUser 旧数据库用户数据
     * @param accountName 账号名称
     * @param type        账号类型
     * @param password    账号密码
     */
    private void checkAndBuildPhoneAccount(
            OldCoreUser oldCoreUser,
            String accountName,
            String type,
            String password
    ) {
        // 查询是否已经存在该手机号的信息
        var wrapper = new LambdaQueryWrapper<SystemAccount>()
                .eq(SystemAccount::getAccount, accountName)
                .eq(SystemAccount::getType, type);
        var account = systemAccountMapper.selectOne(wrapper);
        // 再次基础上进行修改
        if (account != null) {
            if (!account.getFkUserId().equals(oldCoreUser.getUserId())) {
                throw new BusinessSimpleException(String.format("用户id不一致，旧系统用户id：%s，新系统用户id：%s", oldCoreUser.getUserId(), account.getFkUserId()));
            }
            if (StringUtils.isNotBlank(password) && password.equals(account.getPassword())) {
                account.setPassword(password);
                systemAccountMapper.updateById(account);
            }
            return;
        }
        var newAccount = new SystemAccount();
        newAccount.setAccount(accountName);
        newAccount.setType(type);
        newAccount.setFkUserId(oldCoreUser.getUserId());
        newAccount.setPassword(password);
        // 新增
        systemAccountMapper.insert(newAccount);
    }

    /**
     * 创建用户的基础信息
     *
     * @param user        用户信息
     * @param oldCoreUser 旧数据库用户数据
     * @return 用户信息
     */
    private SystemUser buildCommonUserBaseInfo(SystemUser user, OldCoreUser oldCoreUser) {
        user.setId(oldCoreUser.getUserId());
        user.setLastLogin(oldCoreUser.getUserRegTime());
        user.setGmtCreate(oldCoreUser.getUserRegTime());
        user.setFromType(3);
        // 设置状态的默认值
        user.setIsDisable(0);
        user.setState(1);
        // 修改用户状态 并返回数据
        return userUpdateStateResolveMethod.buildUserState(user, oldCoreUser);
    }

    /**
     * 根据用户id同步信息
     *
     * @param userId 用户id
     */
    public Tuple2<SystemUserInfo, ContactUser> getByUserId(Long userId) {
        // 获取用户信息
        var userInfoWrapper = new LambdaQueryWrapper<SystemUserInfo>().eq(SystemUserInfo::getFkUserId, userId);
        var userInfo = systemUserInfoMapper.selectOne(userInfoWrapper);
        if (userInfo == null) {
            // 查询信息
            var oldCoreUser = oldCoreUserMapper.selectById(userId);
            if (oldCoreUser == null) {
                return null;
            }
            var user = new SystemUser();
            // 处理业务信息
            user.setId(oldCoreUser.getUserId());
            user.setLastLogin(oldCoreUser.getUserLoginTime());
            user.setIsDisable(0);
            user.setState(1);
            userUpdateStateResolveMethod.buildUserState(user, oldCoreUser);
            // 保存信息
            systemUserMapper.insert(user);
            // 手机号账号
            var account = new SystemAccount();
            // 账号详情（手机号）
            account.setType(AccountType.PHONE.type());
            account.setAccount(oldCoreUser.getUserPhone());
            account.setFkUserId(user.getId());
            systemAccountMapper.insert(account);

            if (StringUtils.isNotBlank(oldCoreUser.getUserAccount())) {
                // 账号密码登录账号
                var account2 = new SystemAccount();
                account2.setAccount(oldCoreUser.getUserAccount());
                account2.setType(AccountType.TEXT.type());
                account2.setPassword(oldCoreUser.getUserPwd());
                account2.setFkUserId(userId);
                systemAccountMapper.insert(account2);
            } else {
                if (StringUtils.isNotBlank(oldCoreUser.getUserPhone())) {
                    // 账号密码登录账号
                    var account2 = new SystemAccount();
                    account2.setAccount(oldCoreUser.getUserPhone());
                    account2.setType(AccountType.TEXT.type());
                    account2.setPassword(oldCoreUser.getUserPwd());
                    account2.setFkUserId(userId);
                    systemAccountMapper.insert(account2);
                }
            }
            // 用户详细信息
            userInfo = new SystemUserInfo();
            userInfo.setPhone(oldCoreUser.getUserPhone());
            userInfo.setFkUserId(userId);
            systemUserInfoMapper.insert(userInfo);
            // 保存用户的额外信息
            if (StringUtils.isNotBlank(oldCoreUser.getUserQq()) || StringUtils.isNotBlank(oldCoreUser.getUserWeixin())) {
                var extraInfo = new SystemUserExtraInfo();
                extraInfo.setFkUserId(oldCoreUser.getUserId());
                extraInfo.setQq(oldCoreUser.getUserQq());
                extraInfo.setWechat(oldCoreUser.getUserWeixin());
                systemUserExtraInfoMapper.insert(extraInfo);
            }
            var contactUser = new ContactUser();
            // 联系人
            contactUser.setFkUserId(oldCoreUser.getUserId());
            contactUser.setName(account.getAccount());
            contactUser.setPhone(oldCoreUser.getUserPhone());
            contactUser.setIsDefault(1);
            contactUser.setAllowEdit(1);
            contactUser.setAllowDelete(1);
            contactUserMapper.insert(contactUser);
            return Tuple.of(userInfo, contactUser);
        }
        // 查询联系人信息
        var wrapper = new LambdaQueryWrapper<ContactUser>()
                .eq(ContactUser::getFkUserId, userId)
                .eq(ContactUser::getIsDefault, 1);
        var contactUser = contactUserMapper.selectOne(wrapper);
        return Tuple.of(userInfo, contactUser);
    }

    /**
     * 名称信息
     *
     * @return 名称
     */
    @Override
    public String name() {
        return "user";
    }

}
